package com.retail.core.task;

import cn.hutool.core.util.ObjectUtil;
import com.retail.core.entity.enums.DelFlagEnum;
import com.retail.core.entity.enums.StatusFlagEnum;
import com.retail.core.util.HttpSourceUtil;
import com.retail.system.entity.request.CronTriggersSynchroTimeRequest;
import com.retail.system.entity.vo.CronTriggersVo;
import com.retail.system.service.CronTriggersService;
import com.retail.system.service.CronTriggersSynchroTimeService;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;

/**
 * @author Administrator
 */
public abstract class RetailQuartzJobBean extends QuartzJobBean {

    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        String className = getClass().getName();
        Long triggerId = null;
        if (ignoredIP()) {
            return;
        }

        CronTriggersVo cronTriggersVo = getCronTriggersService().getModelByCronClassName(className);
        if (ObjectUtil.isNotEmpty(cronTriggersVo)) {
            triggerId = cronTriggersVo.getId();
        }

        synchronized (getClass()) {
            Date startTime = new Date();
            try {
                task(jobExecutionContext);
            } catch (Exception e) {
                e.printStackTrace();
            }
            Date endTime = new Date();
            saveTriggerSynchroTime(triggerId, className, endTime, startTime, endTime, (endTime.getTime() - startTime.getTime())/1000);
        }
    }

    private void saveTriggerSynchroTime(Long triggersId, String triggerClass, Date syncTime, Date startTime, Date endTime, Long execTimes) {
        CronTriggersSynchroTimeRequest request = new CronTriggersSynchroTimeRequest();
        request.setTriggersId(triggersId);
        request.setCronTriggersClass(triggerClass);
        request.setSyncTime(syncTime);
        request.setStartTime(startTime);
        request.setEntTime(endTime);
        request.setExecTimes(execTimes);
        request.setStatusFlag(StatusFlagEnum.USE.getValue());
        request.setDelFlag(DelFlagEnum.NO.getValue());
        request.setCreateUser(0L);
        request.setCreateTime(new Date());
        request.setRemark("AUTO");
        getcronTriggersSynchroTimeService().save(request);
    }

    protected abstract CronTriggersService getCronTriggersService();

    protected abstract CronTriggersSynchroTimeService getcronTriggersSynchroTimeService();

    private boolean ignoredIP() {
        String ip = HttpSourceUtil.getLocalIP();
        if (ObjectUtil.contains(ip, "192.168")
        || ObjectUtil.contains(ip, "127.0.0.1")) {
            System.out.println("exit ..." + ip);
            return true;
        }
        return false;
    }

    public abstract void task(JobExecutionContext jobExecutionContext) ;
}
